package com.nervenets.web.controller.handler.user.user;

import com.nervenets.web.controller.handler.Handler;
import com.nervenets.web.entity.MessageCode;
import com.nervenets.web.hibernate.domain.user.Address;

import javax.servlet.http.HttpServletRequest;

public class UserAddressEditHandler extends Handler<UserAddressEditParams> {
    @Override
    public String handle(UserAddressEditParams params, HttpServletRequest request) throws Exception {
        Address address = new Address();
        if (params.getAddressId() > 0) {
            address = userDao.findById(params.getAddressId(), Address.class);
            if (null == address) return errorMessage(MessageCode.code_404, "您编辑的地址不存在");
        }
        address.setUserId(params.getUserId());
        address.setName(params.getName());
        address.setMobile(params.getMobile());
        address.setAreaId(params.getAreaId());
        address.setDetail(params.getDetail());
        address.setDef(params.isDef());

        if (params.isDef()) {
            userDao.getJdbcTemplate().execute("update addresses set def = false where userId = " + params.getUserId());
        }

        userDao.saveOrUpdate(address);

        return successMessage(address);
    }

    @Override
    public String result() throws Exception {
        return successMessage();
    }
}
